package com.runen.infinitemovement.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.App;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.LoginActivity2;
import com.runen.infinitemovement.activity.MyTheLongMarchRoadActivity;
import com.runen.infinitemovement.activity.SpecialPrivilegesActivity;
import com.runen.infinitemovement.activity.StepsForActivity;
import com.runen.infinitemovement.activity.WeTheLongMarchRoadActivity;
import com.runen.infinitemovement.activity.WebActivity;
import com.runen.infinitemovement.adapter.ColumnActivityAdapter;
import com.runen.infinitemovement.adapter.ColumnActivityNameAdapter;
import com.runen.infinitemovement.adapter.MyActivityAdapter;
import com.runen.infinitemovement.adapter.SportsTypeNameAdapter;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EnterActiviEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.RecommendActivityEntity;
import com.runen.infinitemovement.model.entity.StepForEntity;
import com.runen.infinitemovement.model.entity.TodayStepForValueEntity;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.steputil.StepUtil;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import aiven.guide.view.SmartGuide;
import aiven.guide.view.clip.CustomClip;
import aiven.guide.view.face.IntroPanel;
import aiven.guide.view.layer.GuidView;
import aiven.guide.view.util.SmartUtils;
import butterknife.BindView;
import butterknife.ButterKnife;

public class SportsFragment extends Fragment {
    @BindView(R.id.rv_sports_type)
    RecyclerView rvSportsType;
    @BindView(R.id.sports_type_view_pager)
    ViewPager sportsTypeViewPager;
    @BindView(R.id.rv_column_activity)
    RecyclerView rvColumnActivity;
    @BindView(R.id.rv_column_activity_list)
    RecyclerView rvColumnActivityList;
    @BindView(R.id.rv_column_activity_list2)
    RecyclerView rvColumnActivityList2;
    @BindView(R.id.tv_step_num)
    TextView tv_step_num;
    @BindView(R.id.ll_steps_for)
    LinearLayout llStepsFor;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.iv_setting)
    ImageView iv_setting;
    private SportsTypeNameAdapter sportsTypeNameAdapter;
    private ColumnActivityNameAdapter columnActivityNameAdapter;
    private MyActivityAdapter myActivityAdapter;
    private String[] sportsTypeNames = new String[]{"跑步", "健走", "骑行"};
    private String[] columnTypeNames = new String[]{"活动推荐", "正在参与"};
    private List<String> typeList = new ArrayList<>();
    private List<String> columnList = new ArrayList<>();

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_sports, container, false);
            ButterKnife.bind(this, view);
            EventBus.getDefault().register(this);
            initView();
        }
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    private void initView() {
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(getActivity(), new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                llContent.setPadding(0, CommonUtil.getStatusBarHeight(getActivity()), 0, 0);
            }
        });
        iv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SpecialPrivilegesActivity.class));
            }
        });

        mHandler.sendEmptyMessage(1);
        llStepsFor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(getActivity(), StepsForActivity.class);
                startActivityForResult(intent2, 20);
//                startActivity(new Intent(getActivity(), StepsForActivity.class));
            }
        });

        LinearLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        rvSportsType.setLayoutManager(layoutManager);
        sportsTypeNameAdapter = new SportsTypeNameAdapter(getActivity());
        rvSportsType.setAdapter(sportsTypeNameAdapter);
        typeList.clear();
        for (int i = 0; i < sportsTypeNames.length; i++) {
            typeList.add(sportsTypeNames[i]);
        }
        sportsTypeNameAdapter.setNewData(typeList);


        initSportsTypeName();
        sportsTypeNameAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                sportsTypeNameAdapter.setCheckPosition(position);
                sportsTypeNameAdapter.notifyDataSetChanged();
                sportsTypeViewPager.setCurrentItem(position);
            }
        });

        //设置权限引导(此处由于布局限制，需先加载完rvSportsType，再显示引导页)
        if (SharePreferenceUtils.getBoolean(getActivity(), SPCompat.FIRST_START_SPORT, true))
            initSmartGuide();
        //自动兑换步数
//        goFor();


        LinearLayoutManager layoutManager2 = new GridLayoutManager(getActivity(), 2);
        rvColumnActivity.setLayoutManager(layoutManager2);
        columnActivityNameAdapter = new ColumnActivityNameAdapter(getActivity());
        rvColumnActivity.setAdapter(columnActivityNameAdapter);
        /**
         * 活动
         */
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getActivity());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        rvColumnActivityList.setLayoutManager(layoutManager3);
        columnActivityAdapter = new ColumnActivityAdapter(getActivity());
        rvColumnActivityList.setAdapter(columnActivityAdapter);

        columnActivityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (columnActivityAdapter.getData().get(position).activeType == 0) {
                    Intent intent = new Intent(getActivity(), WeTheLongMarchRoadActivity.class);
                    startActivity(intent);
                } else if (columnActivityAdapter.getData().get(position).activeType == 1) {
                    Intent intent = new Intent(getActivity(), MyTheLongMarchRoadActivity.class);
                    intent.putExtra("userId", UserAPI.getUserId());
                    startActivity(intent);
                } else {
                    Intent intent1 = new Intent(getActivity(), WebActivity.class);
                    intent1.putExtra("LINK_URL", String.format(Constant.ACTIVITY_DETAILS_H5,
                            columnActivityAdapter.getData().get(position).activeId, UserAPI.getUserToken()));
                    startActivity(intent1);
                }
            }
        });

        LinearLayoutManager layoutManager4 = new LinearLayoutManager(getActivity());
        layoutManager4.setOrientation(LinearLayoutManager.VERTICAL);
        rvColumnActivityList2.setLayoutManager(layoutManager4);
        myActivityAdapter = new MyActivityAdapter(getActivity());
        rvColumnActivityList2.setAdapter(myActivityAdapter);
        myActivityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), MyTheLongMarchRoadActivity.class);
                intent.putExtra("userId", UserAPI.getUserId());
                startActivity(intent);
            }
        });

        columnList.clear();
        for (int i = 0; i < columnTypeNames.length; i++) {
            columnList.add(columnTypeNames[i]);
        }
        columnActivityNameAdapter.setNewData(columnList);

        columnActivityNameAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                columnActivityNameAdapter.setCheckPosition(position);
                columnActivityNameAdapter.notifyDataSetChanged();
                initColumnTypeName(position);
            }
        });
        initColumnTypeName(0);
    }

    private ColumnActivityAdapter columnActivityAdapter;
    private List<String> stringList = new ArrayList<>();

    private void initColumnTypeName(int position) {
        if (position == 0) {
            rvColumnActivityList.setVisibility(View.VISIBLE);
            rvColumnActivityList2.setVisibility(View.GONE);
            new ActivityAPI().getRecommend(new BaseResultCallback<RecommendActivityEntity>() {
                @Override
                public void onResponse(RecommendActivityEntity response) {
                    if (response.code == 0) {
                        if (response.data != null && response.data.size() > 0) {
                            columnActivityAdapter.setNewData(response.data);
                        }
                    }

                }

                @Override
                public void onError(Throwable e, String body) {
                    if (!TextUtils.isEmpty(body)) {
                        if (body.contains("Invalid access token")) {
                            UserAPI.clearLogin();
                            startActivity(new Intent(getActivity(), LoginActivity2.class));
                        }
                    }
                    super.onError(e, body);
                }
            });
        } else {
            rvColumnActivityList.setVisibility(View.GONE);
            rvColumnActivityList2.setVisibility(View.VISIBLE);
            new ActivityAPI().getEnterActivity(new BaseResultCallback<EnterActiviEntity>() {
                @Override
                public void onResponse(EnterActiviEntity response) {
                    if (response.code == 0) {
                        if (response.data != null && response.data.size() > 0) {
                            myActivityAdapter.setNewData(response.data);
                        }
                    }

                }

                @Override
                public void onError(Throwable e, String body) {
                    if (!TextUtils.isEmpty(body)) {
                        if (body.contains("Invalid access token")) {
                            UserAPI.clearLogin();
                            startActivity(new Intent(getActivity(), LoginActivity2.class));
                        }
                    }
                    super.onError(e, body);
                }
            });
        }
    }

    private void goFor() {
        value = "今日推进<font color='#E22A29'>%s</font>进度值";
        new UserAPI().stepFor(new BaseResultCallback<StepForEntity>() {
            @Override
            public void onResponse(StepForEntity response) {
                if (response.code == 0) {
                    tvProgress.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(response.data.totalCompletionRatePlus * 100) + "%")));
                }
            }
        });
    }

    private void initSportsTypeName() {
        sportsTypeViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                SportsTypeFragment sportsTypeFragment = (SportsTypeFragment) SportsTypeFragment.newInstance(position);
                return sportsTypeFragment;
            }

            @Override
            public int getCount() {
                return typeList.size();
            }
        });
        sportsTypeViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                sportsTypeNameAdapter.setCheckPosition(position);
                sportsTypeNameAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusEntity event) {
        switch (event.getMsg()) {
            case 99:
                initColumnTypeName(0);
                break;
            case EventBusEntity.CODE_110:
                value = "今日推进<font color='#E22A29'>%s</font>进度值";
                double totalCompletionRatePlus = event.getData();
                tvProgress.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(totalCompletionRatePlus * 100) + "%")));
            default:
                break;
        }
    }

    private int steps;
    private boolean isUpStep = true;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                steps = StepUtil.getTodayStep(App.getInstance());
                tv_step_num.setText(String.valueOf(steps));
                if (isUpStep) {
                    if (0 != steps) {
                        onUpDataStep();
                        isUpStep = false;
                    }
                }
                mHandler.sendEmptyMessageDelayed(1, 3000);
            }
            return false;
        }
    });

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
//        handler.removeMessages(1);
    }


    private void onUpDataStep() {
        JSONObject object = new JSONObject();
        try {
            object.put("step", steps);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().upDataStep(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                } else {
//                    initData();
                }
                goFor();
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                }
                super.onError(e, body);
            }
        });
    }

    private String value;

    private void initData() {
        value = "兑换后可推进<font color='#E22A29'>%s</font>进度";
        new UserAPI().getStep(new BaseResultCallback<TodayStepForValueEntity>() {
            @Override
            public void onResponse(TodayStepForValueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        tvProgress.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(response.data.completionRatePlus * 100) + "%")));
                    }
                } else {
                    tvProgress.setText(Html.fromHtml(String.format(value, 0)));
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 20) {
            if (data != null) {
                value = "今日推进<font color='#E22A29'>%s</font>进度值";
                double completionRatePlus = data.getDoubleExtra("completionRatePlus", 0);
                double totalCompletionRatePlus = data.getDoubleExtra("totalCompletionRatePlus", 0);
                tvProgress.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(totalCompletionRatePlus * 100) + "%")));
            }
        }
    }

    private void initSmartGuide() {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        iv_setting.measure(w, h);
        rvSportsType.measure(w, h);
        int width = iv_setting.getMeasuredWidth() + CommonUtil.dp2px(getActivity(), 20);

        float y = CommonUtil.getStatusBarHeight(getActivity()) + CommonUtil.dp2px(getActivity(), 5);
        SmartGuide.newGuide(getActivity())
                .newLayer("sport")
                .buildCustomClip(new SmartGuide.ClipPositionBuilder<CustomClip>() {
                    @Override
                    public CustomClip buildTarget() {//返回一个被挖空的镂空区域实例
                        //构建镂空区域图形，支持CustomClip 和 ViewRectClip，ViewRectClip 后面第二个实例紫色音乐图标实例说明
                        return CustomClip.newClipPos()
                                //设置异形图片(实现见第三个按钮)
                                //.asIrregularShape(getApplicationContext(),R.mipmap.test_img)   这里屏蔽了是因为在实例3中是实现，标识一个要挖空一个异形区域，由不规则图片区域决定
                                .setAlignX(SmartGuide.AlignX.ALIGN_RIGHT)//设置定位水平定位偏向（这里的偏向是屏幕根而言，类似于RelativeLayout的align,局屏幕顶部，左边、右边、下边 自己定义）
                                .setAlignY(SmartGuide.AlignY.ALIGN_TOP)//设置定位垂直定位偏向 （这里的偏向是屏幕根而言，类似于RelativeLayout的align）
                                .setEventPassThrough(false)//镂空区域是否事件穿透，上面说的需要个人中心图标自己响应事件，设置后后面的点击事件 clipClicked 将不再响应改Tag的事件
                                .setOffsetX(SmartUtils.dip2px(getActivity(), 5))//根据水平定位偏向设置偏移，类似于margin，如果未ALIGN_LEFT,则是距离屏幕左侧偏移量，如果是ALIGN_RIGHT 则是距离屏幕右侧偏移量
                                .setOffsetY(y) //同offsetX基本相同的意思，只不过这个是垂直方向的
                                .setClipSize(width, width) //设置镂空裁剪区域尺寸,这里一定要指定，否则没有
                                .clipRadius(width / 2);//设置镂空区域半径，默认是90度直角，也就是方形的，这里显示一个圆圈，所以半径是宽高的一半，也可以自己指定一个圆角值
                    }
                })
                .buildIntroPanel(new SmartGuide.IntroPanelBuilder() {
                    @Override
                    public IntroPanel buildFacePanel() {
                        return IntroPanel.newIntroPanel(getActivity())
                                .setIntroBmp(R.mipmap.ico_sport_guide)//设置一个图片，这里就是刚说那张说明图片
                                //这里的Align 同CustomClip的Align有点点区别，这里的Align不再是界面根布局为标准，这里是clip的镂空区域，也就是局于镂空区域的，左边、上面、下面、右面，自己定义
                                //类似与RelativeLayout的相对布局toLeft、toRight、above、below
                                .setAlign(SmartGuide.AlignX.ALIGN_LEFT, SmartGuide.AlignY.ALIGN_BOTTOM)
                                .setSize(SmartUtils.dip2px(getActivity(), 218), SmartUtils.dip2px(getActivity(), 110)) //设置图片展示的尺寸
                                .setOffset(SmartUtils.dip2px(getActivity(), 10), SmartUtils.dip2px(getActivity(), 10));//设置水平和垂直方向的偏移值，这里要注意根据Align来计算，也相当于margin，不过是相对于clip镂空区域
                    }
                })
                //添加点击事件
                .setOnGuidClickListener(new SmartGuide.OnGuidClickListener() {
                    @Override
                    public boolean emptyErrorClicked(SmartGuide smartGuide) {//点击蒙层中无裁剪和无镂空区域部分，部分需求是点击旁边无内容区域蒙层直接消失，所以这里增加了
                        return true;//返回true，引导消失，false不消失
                    }

                    @Override
                    public void clipClicked(SmartGuide guide, GuidView view, String tag) {
                        //由于设置了setEventPassThrough 为true，所以tag为TAG_USER_HEADER 的时候这里这个方法不会回调
                        if (tag.equals("sport")) {
                            Intent intent = new Intent(getActivity(), SpecialPrivilegesActivity.class);
                            startActivity(intent);
                        }
                        guide.dismiss();
                    }

                    @Override
                    public void introClicked(SmartGuide guide, GuidView view, String tag) {
                        //点击文字区域
                    }
                })
                .show();
        SharePreferenceUtils.putBoolean(getActivity(), SPCompat.FIRST_START_SPORT, false);
    }
}
